<template>
  <a-card :bordered="false">
    <!-- 计件收入统计区域 -->
    <div class="income-stats-wrapper" style="margin-bottom: 16px">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-card size="small" :bordered="true">
            <a-statistic
              title="今日计件收入"
              :value="incomeStats.todayIncome"
              :precision="2"
              suffix="元"
              :value-style="{ color: '#3f8600' }"
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card size="small" :bordered="true">
            <a-statistic
              title="本月计件收入"
              :value="incomeStats.monthIncome"
              :precision="2"
              suffix="元"
              :value-style="{ color: '#1890ff' }"
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card size="small" :bordered="true">
            <a-statistic
              title="待结算工资"
              :value="incomeStats.pendingIncome"
              :precision="2"
              suffix="元"
              :value-style="{ color: '#cf1322' }"
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card size="small" :bordered="true">
            <a-statistic
              title="完成任务数"
              :value="incomeStats.completedTasks"
              suffix="个"
              :value-style="{ color: '#722ed1' }"
            />
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="计划名称">
              <a-input placeholder="请输入计划名称" v-model="queryParam.planName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="工种">
              <j-dict-select-tag
                placeholder="请选择工种"
                v-model="queryParam.workTypeId"
                dictCode="mes_work_type,work_type_name,id"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="任务状态">
              <j-dict-select-tag placeholder="请选择状态" v-model="queryParam.status" dictCode="task_status" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAvailableTasks" type="primary" icon="eye"> 可领取任务 </a-button>
      <a-button @click="handleMyTasks" type="primary" icon="user" style="margin-left: 8px"> 我的任务 </a-button>
      <a-switch v-model="useGroupedView" @change="handleViewModeChange" style="margin-left: 16px" />
      <span style="margin-left: 8px">分组视图</span>
    </div>

    <!-- 分组视图 -->
    <div v-if="useGroupedView" class="grouped-task-view">
      <a-spin :spinning="loading">
        <!-- 生产计划分组列表 -->
        <div v-for="planGroup in groupedData" :key="planGroup.planId" class="plan-group-card">
          <a-card size="small" :bordered="true" style="margin-bottom: 16px">
            <!-- 生产计划头部 -->
            <div slot="title" class="plan-header" @click="togglePlanExpansion(planGroup)">
              <a-icon :type="planGroup.expanded ? 'down' : 'right'" style="margin-right: 8px" />
              <span class="plan-title">{{ planGroup.planName }}</span>
              <a-tag color="blue" style="margin-left: 8px">{{ planGroup.planNo }}</a-tag>
              <div class="plan-stats">
                <a-progress
                  :percent="Math.round(planGroup.progress)"
                  size="small"
                  style="width: 120px; margin-left: 16px"
                  :status="planGroup.progress === 100 ? 'success' : 'active'"
                />
                <span style="margin-left: 8px"> {{ planGroup.completedTasks }}/{{ planGroup.totalTasks }} 任务 </span>
                <span style="margin-left: 8px">
                  {{ planGroup.completedQuantity }}/{{ planGroup.totalQuantity }} 数量
                </span>
              </div>
            </div>

            <!-- 工种分组列表 -->
            <div v-if="planGroup.expanded" class="work-type-groups">
              <div v-for="workTypeGroup in planGroup.workTypes" :key="workTypeGroup.workTypeId" class="work-type-group">
                <div class="work-type-header" @click="toggleWorkTypeExpansion(workTypeGroup)">
                  <a-icon :type="workTypeGroup.expanded ? 'down' : 'right'" style="margin-right: 8px" />
                  <a-tag color="green">{{ workTypeGroup.workTypeName }}</a-tag>
                  <div class="work-type-stats">
                    <a-progress
                      :percent="Math.round(workTypeGroup.progress)"
                      size="small"
                      style="width: 100px; margin-left: 12px"
                      :status="workTypeGroup.progress === 100 ? 'success' : 'active'"
                    />
                    <span style="margin-left: 8px">
                      {{ workTypeGroup.completedTasks }}/{{ workTypeGroup.totalTasks }} 任务
                    </span>
                  </div>
                </div>

                <!-- 具体任务列表 -->
                <div v-if="workTypeGroup.expanded" class="task-list">
                  <a-table
                    :columns="taskColumns"
                    :dataSource="workTypeGroup.tasks"
                    :pagination="false"
                    size="small"
                    rowKey="id"
                    :scroll="{ x: true }"
                  >
                    <template slot="collaborationType" slot-scope="text">
                      <a-tag :color="text == 0 ? 'green' : text == 1 ? 'blue' : 'orange'">
                        {{ text == 0 ? '独立完成' : text == 1 ? '协作完成' : '分段完成' }}
                      </a-tag>
                    </template>

                    <template slot="allowPartialClaim" slot-scope="text">
                      <a-badge v-if="text" status="success" text="是" />
                      <a-badge v-else status="default" text="否" />
                    </template>

                    <template slot="status_dictText" slot-scope="text, record">
                      <a-tag :color="getStatusColor(record.status)">{{ text || getStatusText(record.status) }}</a-tag>
                    </template>

                    <span slot="taskAction" slot-scope="text, record">
                      <a @click="handleDetail(record)">详情</a>
                      <a-divider type="vertical" />
                      <a @click="handleExecutionStatus(record)">执行情况</a>
                    </span>
                  </a-table>
                </div>
              </div>
            </div>
          </a-card>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper" style="text-align: center; margin-top: 16px">
          <a-pagination
            v-model="ipagination.current"
            :total="ipagination.total"
            :pageSize="ipagination.pageSize"
            :showSizeChanger="true"
            :showQuickJumper="true"
            :showTotal="(total, range) => `显示 ${range[0]}-${range[1]} 共 ${total} 条`"
            @change="handleTableChange"
            @showSizeChange="handleTableChange"
          />
        </div>
      </a-spin>
    </div>

    <!-- 传统表格视图 -->
    <div v-else>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <span slot="taskAction" slot-scope="text, record">
          <a @click="handleDetail(record)">详情</a>
          <a-divider type="vertical" />
          <a @click="handleExecutionStatus(record)">执行情况</a>
        </span>
      </a-table>
    </div>

    <!-- 任务详情模态框 -->
    <task-detail-modal ref="taskDetailModal" @ok="modalFormOk"></task-detail-modal>
    <!-- 任务领取模态框 -->
    <task-claim-modal ref="taskClaimModal" @ok="modalFormOk"></task-claim-modal>
    <!-- 任务完成模态框 -->
    <task-complete-modal ref="taskCompleteModal" @ok="modalFormOk"></task-complete-modal>
    <!-- 进度更新模态框 -->
    <task-progress-modal ref="taskProgressModal" @ok="modalFormOk"></task-progress-modal>
    <!-- 可领取任务模态框 -->
    <available-tasks-modal ref="availableTasksModal" @ok="modalFormOk"></available-tasks-modal>
    <!-- 执行情况模态框 -->
    <task-execution-modal ref="taskExecutionModal" @ok="modalFormOk"></task-execution-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import TaskDetailModal from './modules/TaskDetailModal.vue'
import TaskClaimModal from './modules/TaskClaimModal.vue'
import TaskCompleteModal from './modules/TaskCompleteModal.vue'
import TaskProgressModal from './modules/TaskProgressModal.vue'
import AvailableTasksModal from './modules/AvailableTasksModal.vue'
import TaskExecutionModal from './modules/TaskExecutionModal.vue'
import { getAction, postAction } from '@/api/manage'
import { mapGetters } from 'vuex'

export default {
  name: 'TaskList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    TaskDetailModal,
    TaskClaimModal,
    TaskCompleteModal,
    TaskProgressModal,
    AvailableTasksModal,
    TaskExecutionModal,
  },
  data() {
    return {
      description: '生产任务管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '任务编号',
          align: 'center',
          dataIndex: 'id',
        },
        {
          title: '生产计划',
          align: 'center',
          dataIndex: 'planName',
        },
        {
          title: '工种名称',
          align: 'center',
          dataIndex: 'workTypeName',
        },
        {
          title: '工序顺序',
          align: 'center',
          dataIndex: 'sequence',
        },
        {
          title: '任务数量',
          align: 'center',
          dataIndex: 'taskQuantity',
        },
        {
          title: '完成数量',
          align: 'center',
          dataIndex: 'completedQuantity',
        },
        {
          title: '计划开始日期',
          align: 'center',
          dataIndex: 'planStartDate',
        },
        {
          title: '计划结束日期',
          align: 'center',
          dataIndex: 'planEndDate',
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status_dictText',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'taskAction' },
        },
      ],
      url: {
        list: '/mes/task/list',
        delete: '/mes/task/delete',
        deleteBatch: '/mes/task/deleteBatch',
        exportXlsUrl: '/mes/task/exportXls',
        importExcelUrl: 'mes/mesProductionPlanTask/importExcel',
        claim: '/mes/task/claim',
        start: '/mes/task/start',
        pause: '/mes/task/pause',
        resume: '/mes/task/resume',
        complete: '/mes/task/complete',
        updateProgress: '/mes/task/update-progress',
        available: '/mes/task/available',
        myTasks: '/mes/task/my-tasks',
      },
      dictOptions: {},
      superFieldList: [],
      incomeStats: {
        todayIncome: 0,
        monthIncome: 0,
        pendingIncome: 0,
        completedTasks: 0,
      },
      // 分组视图相关数据
      useGroupedView: false,
      groupedData: [],
      groupedPagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      // 任务表格列配置（用于分组视图中的嵌套表格）
      taskColumns: [
        {
          title: '任务编号',
          dataIndex: 'id',
          width: 120,
        },
        {
          title: '任务数量',
          dataIndex: 'taskQuantity',
          width: 100,
        },
        {
          title: '完成数量',
          dataIndex: 'completedQuantity',
          width: 100,
        },
        {
          title: '协作类型',
          dataIndex: 'collaborationType',
          width: 100,
          scopedSlots: { customRender: 'collaborationType' },
        },
        {
          title: '最大参与数',
          dataIndex: 'maxParticipants',
          width: 100,
        },
        {
          title: '允许部分领取',
          dataIndex: 'allowPartialClaim',
          width: 120,
          scopedSlots: { customRender: 'allowPartialClaim' },
        },
        {
          title: '状态',
          dataIndex: 'status_dictText',
          width: 100,
          scopedSlots: { customRender: 'status_dictText' },
        },
        {
          title: '领取员工',
          dataIndex: 'claimedEmployeeName',
          width: 120,
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 200,
          scopedSlots: { customRender: 'taskAction' },
        },
      ],
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    currentUser() {
      return this.userInfo || {}
    },
  },
  created() {
    this.getSuperFieldList()
    this.loadIncomeStats()
  },
  methods: {
    initDictConfig() {
      // 初始化字典配置
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'planId', text: '生产计划ID' })
      fieldList.push({ type: 'string', value: 'workTypeId', text: '工种ID' })
      fieldList.push({ type: 'string', value: 'workTypeCode', text: '工种编码' })
      fieldList.push({ type: 'string', value: 'workTypeName', text: '工种名称' })
      fieldList.push({ type: 'int', value: 'sequence', text: '工序顺序' })
      fieldList.push({ type: 'int', value: 'taskQuantity', text: '任务数量' })
      fieldList.push({ type: 'int', value: 'completedQuantity', text: '完成数量' })
      fieldList.push({ type: 'date', value: 'planStartDate', text: '计划开始日期' })
      fieldList.push({ type: 'date', value: 'planEndDate', text: '计划结束日期' })
      fieldList.push({ type: 'date', value: 'actualStartDate', text: '实际开始日期' })
      fieldList.push({ type: 'date', value: 'actualEndDate', text: '实际结束日期' })
      fieldList.push({ type: 'int', value: 'status', text: '状态' })
      fieldList.push({ type: 'string', value: 'claimedEmployeeId', text: '领取员工ID' })
      fieldList.push({ type: 'string', value: 'claimedEmployeeName', text: '领取员工姓名' })
      fieldList.push({ type: 'date', value: 'claimedTime', text: '领取时间' })
      fieldList.push({ type: 'string', value: 'remark', text: '备注' })
      this.superFieldList = fieldList
    },
    handleDetail: function (record) {
      this.$refs.taskDetailModal.detail(record)
      this.$refs.taskDetailModal.title = '详情'
    },
    handleClaim: function (record) {
      this.$refs.taskClaimModal.claim(record)
    },
    handleExecutionStatus: function (record) {
      this.$refs.taskExecutionModal.show(record)
    },
    handleStart: function (record) {
      let that = this
      this.$confirm({
        title: '确认操作',
        content: '是否确定开始执行任务？',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: function () {
          postAction(that.url.start, { taskId: record.id, employeeId: that.currentUser.id }).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadData()
            } else {
              that.$message.warning(res.message)
            }
          })
        },
      })
    },
    handlePause: function (record) {
      let that = this
      this.$confirm({
        title: '确认操作',
        content: '是否确定暂停任务？',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: function () {
          postAction(that.url.pause, { taskId: record.id, employeeId: that.currentUser.id }).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadData()
            } else {
              that.$message.warning(res.message)
            }
          })
        },
      })
    },
    handleResume: function (record) {
      let that = this
      this.$confirm({
        title: '确认操作',
        content: '是否确定恢复任务？',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: function () {
          postAction(that.url.resume, { taskId: record.id, employeeId: that.currentUser.id }).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadData()
            } else {
              that.$message.warning(res.message)
            }
          })
        },
      })
    },
    handleComplete: function (record) {
      this.$refs.taskCompleteModal.complete(record)
    },
    handleUpdateProgress: function (record) {
      this.$refs.taskProgressModal.updateProgress(record)
    },
    handleAvailableTasks: function () {
      this.$refs.availableTasksModal.show()
    },
    handleMyTasks: function () {
      // 筛选显示我的任务
      this.queryParam.claimedEmployeeId = this.currentUser.id
      this.loadData()
    },
    loadIncomeStats: function () {
      // 加载员工计件收入统计数据
      if (!this.currentUser.id) {
        return
      }
      getAction('/mes/employeePieceWage/stats', { employeeId: this.currentUser.id })
        .then((res) => {
          if (res.success) {
            this.incomeStats = {
              todayIncome: res.result.todayIncome || 0,
              monthIncome: res.result.monthIncome || 0,
              pendingIncome: res.result.pendingIncome || 0,
              completedTasks: res.result.completedTasks || 0,
            }
          }
        })
        .catch(() => {
          // 静默处理错误，使用默认值
          this.incomeStats = {
            todayIncome: 0,
            monthIncome: 0,
            pendingIncome: 0,
            completedTasks: 0,
          }
        })
    },
    // 分组视图相关方法
    handleViewModeChange(value) {
      this.useGroupedView = value
      if (value) {
        this.loadGroupedData()
      }
    },

    // 状态相关方法
    getStatusText(status) {
      const statusMap = {
        0: '待领取',
        1: '已领取',
        2: '进行中',
        3: '已完成',
        4: '已暂停',
        5: '部分完成',
      }
      return statusMap[status] || '未知'
    },

    getStatusColor(status) {
      const colorMap = {
        0: 'default',
        1: 'processing',
        2: 'warning',
        3: 'success',
        4: 'error',
        5: 'cyan',
      }
      return colorMap[status] || 'default'
    },
    loadGroupedData() {
      this.loading = true
      const params = {
        pageNo: this.groupedPagination.current,
        pageSize: this.groupedPagination.pageSize,
        ...this.queryParam,
      }

      getAction('/mes/task/grouped', params)
        .then((res) => {
          if (res.success) {
            this.groupedData = res.result.records || []
            this.groupedPagination.total = res.result.total || 0
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    togglePlanExpansion(planGroup) {
      this.$set(planGroup, 'expanded', !planGroup.expanded)
    },
    toggleWorkTypeExpansion(workTypeGroup) {
      this.$set(workTypeGroup, 'expanded', !workTypeGroup.expanded)
    },
    onGroupedPageChange(page, pageSize) {
      this.groupedPagination.current = page
      this.groupedPagination.pageSize = pageSize
      this.loadGroupedData()
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
